package main

import (
	"github.com/gin-gonic/gin"
	"io"
	"log"
	"net"
	"net/http"
	"sync"
	"time"
)

func main() {
	// 配置Gin
	engine := gin.Default()
	go run()
	// 启动 Gin 服务
	srv := &http.Server{
		Addr:    ":888",
		Handler: engine, // 使用自定义的处理器
	}
	err := srv.ListenAndServe()
	if err != nil {
		return
	}
	//var wg sync.WaitGroup
	//wg.Add(1)
	//
	//// 在goroutine中启动服务器
	//go func() {
	//	defer wg.Done()
	//	run()
	//}()
	//
	//// 等待中断信号优雅退出
	//sigs := make(chan os.Signal, 1)
	//signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
	//<-sigs
	//
	//log.Println("接收到终止信号，服务器正在关闭...")
	//wg.Wait() // 等待服务器优雅关闭
	//log.Println("服务器已关闭")
}

func run() {
	// 启动服务器
	listener, err := net.Listen("tcp", ":8888")
	if err != nil {
		log.Fatalf("无法启动服务器: %v", err)
	}
	defer listener.Close()

	log.Println("服务器已启动，监听端口 :8888")

	// 存储客户端连接
	clients := make(map[string]net.Conn)
	clientsMutex := &sync.RWMutex{}

	// 接受客户端连接
	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Printf("接受连接失败: %v", err)
			continue
		}

		clientAddr := conn.RemoteAddr().String()
		log.Printf("客户端 %s 已连接", clientAddr)

		// 存储客户端连接
		clientsMutex.Lock()
		clients[clientAddr] = conn
		clientsMutex.Unlock()

		// 处理客户端连接
		go handleClient(conn, clientAddr, clients, clientsMutex)
	}
}

func handleClient(conn net.Conn, clientAddr string, clients map[string]net.Conn, clientsMutex *sync.RWMutex) {
	defer func() {
		// 从映射中删除客户端
		clientsMutex.Lock()
		delete(clients, clientAddr)
		clientsMutex.Unlock()

		// 关闭连接
		conn.Close()
		log.Printf("客户端 %s 已断开连接", clientAddr)
	}()

	// 设置读取超时
	conn.SetReadDeadline(time.Now().Add(30 * time.Second))

	// 读取客户端数据
	buffer := make([]byte, 1024)
	for {
		// 重置读取超时
		conn.SetReadDeadline(time.Now().Add(30 * time.Second))

		n, err := conn.Read(buffer)
		if err != nil {
			if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
				log.Printf("客户端 %s 读取超时", clientAddr)
			} else if err == io.EOF {
				log.Printf("客户端 %s 正常关闭连接", clientAddr)
			} else {
				log.Printf("客户端 %s 读取错误: %v", clientAddr, err)
			}
			break
		}

		message := string(buffer[:n])
		log.Printf("从客户端 %s 收到消息: %s", clientAddr, message)

		// 发送响应
		_, err = conn.Write([]byte("消息已接收\n"))
		if err != nil {
			log.Printf("向客户端 %s 发送响应失败: %v", clientAddr, err)
			break
		}
	}
}
